package ru.royalgatemagazine.app.show.main;

import ru.royalgatemagazine.app.Debug;
import ru.royalgatemagazine.app.R;
import ru.royalgatemagazine.app.http.HttpSimpleClient;
import ru.royalgatemagazine.app.view.AbstractView;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextUtils;
import android.view.View;

public class MainCatalogView extends AbstractView {
	
	private MainEntity mEntity;
	
	public MainCatalogView(Context context, final MainCatalogController controller) {
		super(context);
		findViewById(R.id.main_item_button).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				controller.onOpenClick(mEntity);
			}
		});
		findViewById(R.id.main_item_pic).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				controller.onOpenClick(mEntity);
			}
		});
	}

	@Override
	protected int layout() {
		return R.layout.main_item;
	}

	public void setEntity(MainEntity entity){
		mEntity = entity;
		setText(R.id.main_item_head, entity.title);
		setText(R.id.main_item_content, entity.text);
		StringBuilder url = new StringBuilder(HttpSimpleClient.PIC_PATH);
		url.append(entity.image);
		if(!TextUtils.isEmpty(entity.image)){
			loadImageAsync(url.toString());
		}
		else{
			Debug.log("MainCatalogView.setEntity()"+"TextUtils.isEmpty(entity.image)");
		}
	}
	
	private void loadImageAsync(final String url){
		setImageResource(R.id.main_item_pic, android.R.drawable.progress_horizontal);
		Runnable r = new Runnable() {
			@Override
			public void run() {
				HttpSimpleClient client = new HttpSimpleClient(getContext());
				final Bitmap b = client.loadBitmap(url);
				if(b!=null){
					MainCatalogView.this.post(
							new Runnable() {
								@Override
								public void run() {
									BitmapDrawable bd = new BitmapDrawable(b);
									setImageDrawable(R.id.main_item_pic, bd);
								}
							}
					);
				}
				else{
					Debug.log("MainCatalogView.loadImageAsync() : bitmap == null");
				}
			}
		};
		Thread t = new Thread(r);
		t.start();
	}
	
	public void clear() {
		setImageDrawable(R.id.main_item_pic, null);
		setText(R.id.main_item_head, "");
		setText(R.id.main_item_content, "");
	}
}
